﻿using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using LitJson;
using Nomo.CoreModule;
using Nomo.UnityCoreModule.Assets;

namespace Nomo.UnityCoreModule.MultiLanguages
{
    /// <summary>
    /// 多语言管理器。
    /// </summary>
    public sealed class MultiLanguageManager : Singleton<MultiLanguageManager>
    {
        private readonly Dictionary<ulong, Dictionary<LanguageType, string>> _multiLanguageStrings;

        /// <summary>
        /// 语言类型。
        /// </summary>
        public LanguageType LanguageType { get; set; } = LanguageType.ZnCh;

        private MultiLanguageManager()
        {
            _multiLanguageStrings = AssetManager.Instance.GetCommonJson("MultiLanguageConfig")
                .Cast<JsonData>()
                .ToDictionary(
                    e => ulong.Parse($"{e["ID"]}", NumberStyles.Integer, NumberFormatInfo.InvariantInfo),
                    e => new Dictionary<LanguageType, string>
                    {
                        [LanguageType.ZnCh] = $"{e[nameof(LanguageType.ZnCh)]}",
                        [LanguageType.EnUs] = $"{e[nameof(LanguageType.EnUs)]}"
                    }
                );
        }

        /// <summary>
        /// 使用默认的语言和指定的键获取多语言字符串。
        /// </summary>
        /// <param name="key">键。</param>
        /// <returns>获取到的多语言字符串。</returns>
        public string GetString(ulong key) => GetString(LanguageType, key);

        /// <summary>
        /// 使用指定的语言和指定的键获取多语言字符串。
        /// </summary>
        /// <param name="languageType">语言。</param>
        /// <param name="key">键。</param>
        /// <returns>获取到的多语言字符串。</returns>
        public string GetString(LanguageType languageType, ulong key) => _multiLanguageStrings.TryGetValue(key, out var values) && values.TryGetValue(languageType, out var value) ? value : key.ToString(NumberFormatInfo.InvariantInfo);
    }
}
